// iisaccelerator - an iis isapi for upgrade web performance
//
// Copyright (C) 2006-2007 - BlueStone  (bluestn@163.com)
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include <TCHAR.h>
#include <ATLBASE.h>
#include "Version.h"

_tstring GetVersionString( )
{
	static TCHAR version[200] = _T("\0");
	
	if( version[0] != _T('\0') )
	{
		return _tstring(version);
	}

	//Fill the version info
	TCHAR fullpath[MAX_PATH+10];
	GetModuleFileName(0, fullpath, MAX_PATH+10);
	
	TCHAR *str = new TCHAR[_tcslen(fullpath)+1];
	strcpy(str,fullpath);

	DWORD tmp=0;
	DWORD len= GetFileVersionInfoSize(str,&tmp);
	LPVOID pBlock=new char[len];
	GetFileVersionInfo(str,0,len,pBlock);
	LPVOID ptr;
	UINT ptrlen;

	_tstring ProductName;
	//Retreive the product name
	
	TCHAR SubBlock[50];
			
	// Structure used to store enumerated languages and code pages.
	struct LANGANDCODEPAGE {
		WORD wLanguage;
		WORD wCodePage;
	} *lpTranslate;

	UINT cbTranslate;
	
	USES_CONVERSION;

	// Read the list of languages and code pages.
	if (VerQueryValue(pBlock, 
				_T("\\VarFileInfo\\Translation"),
				(LPVOID*)&lpTranslate,
				&cbTranslate))
	{
		// Read the file description for each language and code page.
	
		_stprintf( SubBlock, 
	           _T("\\StringFileInfo\\%04x%04x\\FileDescription"),
	           lpTranslate[0].wLanguage,
	           lpTranslate[0].wCodePage);
		// Retrieve file description for language and code page "0". 
		if (VerQueryValue(	pBlock, 
							SubBlock, 
							&ptr, 
							&ptrlen))
		{
			ProductName = A2T((char*)ptr);
		}
	}
	
	//Format the versionstring
	if (VerQueryValue(	pBlock,
						_T("\\"),
						&ptr,
						&ptrlen) )
	{
		VS_FIXEDFILEINFO *fi=(VS_FIXEDFILEINFO*)ptr;
		
		_stprintf(	version,
					_T("%s Version %d.%d.%d.%d"), 
					ProductName.c_str(), 
					fi->dwFileVersionMS>>16,
					fi->dwFileVersionMS&0xFFFF,
					fi->dwFileVersionLS>>16,
					fi->dwFileVersionLS&0xFFFF);		
	}
	
	delete [] str;
	delete [] pBlock;
	
	return _tstring(version);

}